#!/bin/bash

# Usage:
# ./package.sh [--chrome <path to chrome>] src|<branched version>

chrome=/opt/google/chrome/chrome

case $1 in 
  --chrome )
	chrome=$2
	shift 2;;
  --debug | -D )
	DEBUG=1
	shift;;
esac

echo Chrome path: $chrome
if [[ $1 == "src" || (-z "$1") ]]; then
	src=src
	version=trunk
else
	version=$1
	src=../branches/$1
fi
if [[ ! -d $src ]]; then
	echo ERROR: Source directory $src not found.
	exit 1
fi
echo Source directory: $src
echo
echo Packaging...
rsync -aC $src/ tmp

#grep -v "__DEVELOPER__" tmp/scripts/ga.js > tmp/scripts/ga.js.0
sed 's/__DEVELOPER__/__END_USER__/' tmp/scripts/ga.js > tmp/scripts/ga.js.0
mv tmp/scripts/ga.js.0 tmp/scripts/ga.js

package ()
(
	channel=$1
	if [[ $channel == "17" ]]; then
		channel_suffix="-17"
	elif [[ $channel == "dev" ]]; then
		channel_suffix="-dev"
	elif [[ $channel != "stable" ]]; then
		echo Unknown channel: $channel in package.
		exit 1
	fi

	echo Current channel: $channel

	#17 and stable should use the same key
	if [[ $channel == "17" || $channel == "stable" ]]; then
		pempath=./private/stable.pem
	else
		pempath=./private/$channel.pem
	fi

	if [[ -f $pempath ]]; then
		pem=--pack-extension-key=$pempath
	fi
	if $chrome --pack-extension=tmp $pem; then
		crxpathbase=./private
		crxpath=$crxpathbase/riverside-plus-$version$channel_suffix.crx
		mv tmp.crx $crxpath
		if [[ !(-f $pempath) ]]; then
			mv tmp.pem $pempath
		fi
	else
		echo ERROR: Failed to package the extension. 
	fi
)

cp tmp/manifest.json ./manifest.tmp
./manifest_filter.pl --stable ./manifest.tmp > tmp/manifest.json
package stable
./manifest_filter.pl --17 ./manifest.tmp > tmp/manifest.json
package 17
./manifest_filter.pl --dev ./manifest.tmp > tmp/manifest.json
package dev
rm ./manifest.tmp
rm -r -f tmp
if [[ $version == "trunk" ]]; then
	exit 0
fi
#read -p "Are you sure to commit the changes in packaged extensions? [Y,n]"
#if [[ -z $REPLY || $REPLY == "y" || $REPLY == "Y" ]]; then
#	svn commit -m "Packaged the extension for version $version." public
#fi
echo Packaging completed for version $version. Please update updates.xml and commit the change.
